#!/usr/bin/perl -w

use strict;
use warnings;
use diagnostics;

use Getopt::Std;


our($opt_h,$opt_p,$opt_i,$opt_d);
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
my $wgcmd = "/usr/bin/wgcmd";

getopts('h:p:i:d:');

unless ($opt_h && $opt_p && $opt_i && $opt_d) {
    &usage;
    exit -1;
}

# do our work
my $last_data_file = "/tmp/$opt_h.$opt_i.$opt_d.bytes";

my $args = "$wgcmd -u status -p '$opt_p' $opt_h status /network/counter/if_list | xpath -q -e \"/status/network/counter/if_list/if[ifname=\'$opt_i\']/${opt_d}_bytes/text()\"";

my $buf  = `$args`; 

if ($?>>8 > 0) {
    print "error: /network/counter/if_list xpath failed\n";
    exit -1;
}

if (-e $last_data_file) {
    printf("%.3f", get_rate($buf, $last_data_file));
}else{
    #print "file $last_data_file did not exists,create it\n";
    open(LDF, ">$last_data_file") or die "U";
    print LDF $buf;
    close(LDF);
    sleep 1;
    $buf  = `$args`;
    if ($?>>8 > 0) {
        print "error: /network/counter/if_list xpath failed\n";
        exit -1;
    }
    printf("%.3f", get_rate($buf, $last_data_file));
}

sub get_rate{
    my ($data_current, $last_data_file) = @_;
    my $now = time();
    my @fstat = stat($last_data_file);
    my $last_mtime = $fstat[9];
    
    open(LDF, "+<$last_data_file") or die "U";
    
    my @content = <LDF>;
    seek(LDF, 0, 0);
    my $data_last = $content[0];

    # print "$data_current, $data_last, $now, $last_mtime\n";
    # print $data_current-$data_last;
    # print "\n";
    # print $now-$last_mtime;
    # print "\n";

    print LDF $data_current;
    close(LDF);
    return (($data_current - $data_last) * 8 / ($now - $last_mtime))/1024;
}

sub usage {
    print "Usage: $0 -h <host> -p <ro pass> -i <ifname:eth0..> -d <send|recv> #returns N Kbps\n"; 
}
